package net.sk.china.front.service.impl.product;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.sk.china.common.exception.TalkException;
import net.sk.china.common.model.order.StoreOrder;
import net.sk.china.common.model.order.StoreOrderStatus;
import net.sk.china.common.model.product.StoreProductReply;
import net.sk.china.common.model.user.User;
import net.sk.china.common.utils.RedisUtil;
import net.sk.china.common.vo.StoreOrderInfoOldVo;
import net.sk.china.front.constants.Constants;
import net.sk.china.front.dao.order.StoreOrderDao;
import net.sk.china.front.dao.product.StoreProductReplyDao;
import net.sk.china.front.request.order.StoreProductReplyAddRequest;
import net.sk.china.front.service.order.StoreOrderInfoService;
import net.sk.china.front.service.order.StoreOrderService;
import net.sk.china.front.service.product.StoreProductReplyService;
import net.sk.china.front.service.user.UserService;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import java.util.List;

/**
 * StoreProductReplyServiceImpl 接口实现
 * +----------------------------------------------------------------------
 * | Talk To [ 聊来改善地区金融服务环境，助力企业发展 ]
 * +----------------------------------------------------------------------
 * | Copyright (c) 2018-2024 聊来All rights reserved.
 * +----------------------------------------------------------------------
 * | Licensed ( <a href="http://www.apache.org/licenses/LICENSE-2.0">apache</a> )
 * +----------------------------------------------------------------------
 * | @Author: 聊来 <18970881148@qq.com>
 * +----------------------------------------------------------------------
 * | DateTime: 2024/6/13 13:56
 * +----------------------------------------------------------------------
 */

@Service
public class StoreProductReplyServiceImpl extends ServiceImpl<StoreProductReplyDao, StoreProductReply> implements StoreProductReplyService {

    @Resource
    private StoreProductReplyDao dao;

    @Resource
    private StoreOrderDao storeOrderDao;

    private final UserService userService;

    private final StoreOrderInfoService storeOrderInfoService;

    private final TransactionTemplate transactionTemplate;

    private final StoreOrderService storeOrderService;

    private RedisUtil redisUtil;

    public StoreProductReplyServiceImpl(UserService userService, StoreOrderInfoService storeOrderInfoService, TransactionTemplate transactionTemplate,
                                        StoreOrderService storeOrderService, RedisUtil redisUtil) {
        this.userService = userService;
        this.storeOrderInfoService = storeOrderInfoService;
        this.transactionTemplate = transactionTemplate;
        this.storeOrderService = storeOrderService;
        this.redisUtil = redisUtil;
    }

    /**
     * 创建订单评价
     * @param request 请求参数
     * @return {@code boolean}
     */
    @Override
    public boolean create(StoreProductReplyAddRequest request) {
        User user = userService.getUserInfo();
        StoreOrder storeOrder = storeOrderDao.getByOderId(request.getOrderNo());
        if (ObjectUtil.isNull(storeOrder) || !storeOrder.getUid().equals(user.getUid())) {
            throw new TalkException("该订单不存在");
        }
        StoreProductReply storeProductReply = new StoreProductReply();
        BeanUtils.copyProperties(request, storeProductReply);
        storeProductReply.setOid(storeOrder.getId());
        Long count = checkIsReply(storeProductReply);
        storeProductReply.setAvatar(user.getAvatar());
        storeProductReply.setNickname(user.getNickname());
        if (StringUtils.isNotBlank(request.getPics())) {
            String pics = request.getPics().replace("[\"","").replace("\"]","")
                    .replace("\"","");
            storeProductReply.setPics(ArrayUtils.toString(pics));
        }
        Boolean execute = transactionTemplate.execute(e -> {
            save(storeProductReply);
            //修改订单信息
            completeOrder(storeProductReply, count, storeOrder);
            return Boolean.TRUE;
        });
        if (!execute) {
            throw new TalkException("评价订单失败");
        }
        return true;
    }

    /**
     * 查询是否已经回复
     * @param unique skuId
     * @param orderId 订单id
     * @return {@code boolean}
     */
    @Override
    public boolean isReply(String unique, Integer orderId) {
        LambdaQueryWrapper<StoreProductReply> lqw = new LambdaQueryWrapper<>();
        lqw.eq(StoreProductReply::getUnique, unique);
        lqw.eq(StoreProductReply::getOid, orderId);
        List<StoreProductReply> replyList = dao.selectList(lqw);
        if (CollUtil.isEmpty(replyList)) {
            return false;
        }
        return true;
    }

    /**
     * 检测当前商品是否可以评论
     * @param storeProductReply 评价
     * @return {@code Long}
     */
    private Long checkIsReply(StoreProductReply storeProductReply) {

        //查看商品信息
        List<StoreOrderInfoOldVo> orderInfoVoList = storeOrderInfoService.getOrderListByOrderId(storeProductReply.getOid());
        if (null == orderInfoVoList || orderInfoVoList.size() < 1) {
            throw new TalkException("没有找到商品信息");
        }

        boolean findResult = false;
        for (StoreOrderInfoOldVo orderInfoVo : orderInfoVoList) {
//            Integer productId = orderInfoVo.getInfo().getInteger("product_id");
            Integer productId = orderInfoVo.getInfo().getProductId();
            if (productId < 1) {
                continue;
            }

            if (storeProductReply.getProductId().equals(productId)) {
                findResult = true;
                break;
            }
        }

        if (!findResult) {
            throw new TalkException("没有找到商品信息");
        }

        //商品是否已评价
        Long replyCount = getReplyCountByEntity(storeProductReply, false);
        if (replyCount > 0) {
            throw new TalkException("该商品已评价");
        }

        return (long) orderInfoVoList.size();
    }

    /**
     * 获取评论信息
     * @param request 请求参数
     * @param isAll 是否读取全部
     * @return {@code Long}
     */
    private Long getReplyCountByEntity(StoreProductReply request, boolean isAll) {
        LambdaQueryWrapper<StoreProductReply> query = new LambdaQueryWrapper<>();
        query.eq(StoreProductReply::getOid, request.getOid());
//        .eq(StoreProductReply::getUnique, request.getUnique());
        if (null != request.getUid()) {
            query.eq(StoreProductReply::getUid, request.getUid());
        }
        if (!isAll) {
            query.eq(StoreProductReply::getProductId, request.getProductId());

        }
        return dao.selectCount(query);
    }

    /**
     * 如果所有的都已评价，那么订单完成
     */
    private void completeOrder(StoreProductReply storeProductReply, Long count, StoreOrder storeOrder) {
        Long replyCount = getReplyCountByEntity(storeProductReply, true);

        if (replyCount.equals(count)) {
            //全部商品都已评价
            storeOrder.setStatus(Constants.ORDER_STATUS_INT_COMPLETE);
            storeOrderService.updateById(storeOrder);
            redisUtil.lPush(Constants.ORDER_TASK_REDIS_KEY_AFTER_COMPLETE_BY_USER, storeOrder.getId());
        }
    }
}
